package com.dzbh.cdsdriver.ui;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.provider.Settings;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.Window;
import android.view.WindowManager;

import com.ashokvarma.bottomnavigation.BottomNavigationBar;
import com.ashokvarma.bottomnavigation.BottomNavigationItem;
import com.dzbh.cdsdriver.R;
import com.dzbh.cdsdriver.service.MyLocationService;
import com.dzbh.cdsdriver.utils.Utils;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements BottomNavigationBar.OnTabSelectedListener {

    private List<Fragment> fragments;
    private Context mContext;
    private boolean isLogin = false;
    /**
     * 最大的屏幕亮度
     */
    float maxLight;
    /**
     * 当前的亮度
     */
    float currentLight;

    /**
     * 用来控制屏幕亮度
     */
    Handler handler;

    /**
     * 延时时间
     */
    long DenyTime = 1 * 60 * 1000L;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        getSupportActionBar().hide();// 隐藏ActionBar
        setContentView(R.layout.activity_main);
        mContext = this;
        fragments = new ArrayList<>();
        SharedPreferences mSharedPreferences = mContext.getSharedPreferences(Utils.FILENAME, MODE_PRIVATE);
        isLogin = mSharedPreferences.getBoolean(Utils.LOG_FLAG, false);
        initView();
        initGPS();
        handler = new Handler(Looper.getMainLooper());
        maxLight = getLightness();
        /*Intent intent = new Intent(this, MonitorService.class);
        startService(intent);*/

        /*PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY,
                "uXdtyBCRxexqvYDISbMtRLlBfG5Lv4s0");*/
        /*Intent intent = new Intent(mContext, MyLocationService.class);
        mContext.startService(intent);*/
    }

    private void initGPS() {
        LocationManager locationManager = (LocationManager)
                mContext.getSystemService(Context.LOCATION_SERVICE);
        // 判断GPS模块是否开启，如果没有则开启
        if (!locationManager
                .isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
            dialog.setMessage("请打开GPS");
            dialog.setPositiveButton("确定",
                    new android.content.DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface arg0, int arg1) {

                            // 转到手机设置界面，用户设置GPS
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivityForResult(intent, 0); // 设置完成后返回到原来的界面

                        }
                    });
            dialog.setNeutralButton("取消", new android.content.DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface arg0, int arg1) {
                    arg0.dismiss();
                    finish();
                }
            } );
            dialog.show();
        }
    }

    private void initView() {

        //得到BottomNavigationBar控件
        BottomNavigationBar navigationBar = (BottomNavigationBar) findViewById(R.id.bottom_navigation_bar);
        //设置BottomNavigationBar的模式，会在下面详细讲解
        navigationBar.setMode(BottomNavigationBar.MODE_DEFAULT);
        //设置BottomNavigationBar的背景风格，后面详细讲解
        navigationBar.setBackgroundStyle(BottomNavigationBar.BACKGROUND_STYLE_STATIC);

        int defaultPos = 0;
        if(isLogin){
            defaultPos = 1;
        }

        //我这里增加了3个Fragment
        //BottomNavigationItem("底部导航ico","底部导航名字")
        navigationBar.addItem(new BottomNavigationItem(R.drawable.ic_logout, R.string.login)
                .setActiveColorResource(R.color.colorPrimary))
                .addItem(new BottomNavigationItem(R.drawable.ic_before, R.string.before_transport)
                        .setActiveColorResource(R.color.colorPrimary))
                .addItem(new BottomNavigationItem(R.drawable.ic_in, R.string.in_transport)
                        .setActiveColorResource(R.color.colorPrimary))
                .setFirstSelectedPosition(defaultPos)//默认选择索引为0的菜单
                .initialise();//对导航进行重绘

        fragments = getFragments();
        setDefaultFragment();
        navigationBar.setTabSelectedListener(this);
    }

    private void setDefaultFragment() {

        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        Log.d("dong", "isLogin:" + isLogin);
        if(isLogin){
            transaction.replace(R.id.id_content, new BeforeThansFragment());
        }else {
            transaction.replace(R.id.id_content, new LogoutFragment());
        }
        transaction.commit();
    }

    private List<Fragment> getFragments() {

        List<Fragment> fragments = new ArrayList<>();
        fragments.add(new LogoutFragment());
        fragments.add(new BeforeThansFragment());
        fragments.add(new InThansFragment());
        return fragments;
    }

    @Override
    protected void onPause() {
        super.onPause();
        stopSleepTask();
    }

    @Override
    protected void onResume() {
        super.onResume();
        startSleepTask();
    }

    @Override
    public void onTabSelected(int position) {

        if (fragments != null) {
            if (position < fragments.size()) {

                FragmentManager fm = getSupportFragmentManager();
                FragmentTransaction ft = fm.beginTransaction();
                Fragment fragment = fragments.get(position);
                ft.replace(R.id.id_content, fragment);
                ft.commitAllowingStateLoss();//选择性的提交，和commit有一定的区别，他不保证数据完整传输
            }
        }
    }

    public void startLocationService(){
        Intent intent = new Intent(mContext, MyLocationService.class);
        startService(intent);
    }

    public void stopLocationService(){
        Intent intent = new Intent(mContext, MyLocationService.class);
        stopService(intent);
    }

    /**
     * 设置亮度
     * @param light
     */
    void setLight(int light) {
        currentLight = light;
        WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
        localLayoutParams.screenBrightness = (light / 500.0F);
        getWindow().setAttributes(localLayoutParams);
    }

    /**
     * 获取亮度
     *
     * @return
     */
    float getLightness() {
        WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
        float light = localLayoutParams.screenBrightness;
        return light;
    }

    /**
     * 开启休眠任务
     */
    void startSleepTask() {
        setLight((int) maxLight);
        handler.removeCallbacks(sleepWindowTask);
        handler.postDelayed(sleepWindowTask, DenyTime);
    }

    /**
     * 结束休眠任务
     */
    void stopSleepTask() {
        handler.removeCallbacks(sleepWindowTask);
    }

    /**
     * 休眠任务
     */
    Runnable sleepWindowTask = new Runnable() {
        @Override
        public void run() {
            setLight(1);
        }
    };

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (currentLight == 1) {
            startSleepTask();
        }
        return super.dispatchTouchEvent(ev);
    }


    @Override
    public void onTabUnselected(int position) {

    }

    @Override
    public void onTabReselected(int position) {

    }
}
